package com.hrt.serial.modbus;

import com.btcode.common.ByteUnit;

/**
 * modbus串口数据对象，用于处理粘包问题
 * 
 * @author gislin
 *
 */
public class ModbusDataFrameDecoderTTMB extends ModbusDataFrameDecoderBase {

    private final int msgMinLength = 9;
    private final int dataLengthBytePos = 3;
    
    public ModbusDataFrameDecoderTTMB(byte[] msg) {
        this.msg = msg;
    }

    public byte[] next() {

        if (msg.length < msgMinLength) {
            throw new MsgLengthException("数据长度不足");
        }

        int dataByteLength = ByteUnit.ConvertByteToInt8(msg[dataLengthBytePos]);

        int expectMsgByteLength = 1 + 1 + 2 + dataByteLength + 2;

        if ((msg.length - readedPosition) < expectMsgByteLength) {
            throw new MsgLengthException("数据长度不足");
        }

        byte[] targetMsg = new byte[expectMsgByteLength];

        System.arraycopy(msg, readedPosition, targetMsg, 0, expectMsgByteLength);

        if (!ModbusCRCUnit.crcCheck(targetMsg)) {
            throw new CRCException("CRC验证不通过");
        }

        readedPosition += expectMsgByteLength;

        return targetMsg;
    }

}
